package com.itheima.reggie_auto.controller;

import com.itheima.reggie_auto.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {

        //1.获取源文件名字后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() +suffix;

        //判断文件路径时是否存在
        File f = new File(basePath);

        //2.将临时文件保存到指定磁盘目录
        try {
            file.transferTo(new File(basePath+ fileName));

        } catch (Exception e) {
            e.printStackTrace();
        }

        //3.返回文件名
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //根据文件名从本地磁盘下载
        try {
            FileInputStream fis = new FileInputStream(basePath+name);
            ServletOutputStream os = response.getOutputStream();

            //数据对拷
            //响应数据
           /* int len;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes,0,len);
            }*/

            IOUtils.copy(fis,os);

            //释放资源
            fis.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
